package com.zhaoguang.car.interceptor;

import com.zhaoguang.car.common.AuthorizationException;
import com.zhaoguang.car.entity.UserToken;
import com.zhaoguang.car.manager.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("拦截器---检查登录认证");
        String userId = request.getHeader("UserId");
        String carToken = request.getHeader("CarToken");
        if (carToken != null) {
            boolean result = tokenManager.checkToken(Integer.parseInt(userId), carToken);
            if (result) {
                return true;
            } else {
                throw new AuthorizationException("登录已失效");
            }
        } else {
            throw new AuthorizationException("登录已失效");
        }

    }
}
